import urllib.request
import urllib.parse
import os
import time
import random

# 目标PDF文件名
pdf_filename = '人工智能对就业市场的影响数据集.pdf'
# 保存路径
save_dir = r'd:\D'
pdf_save_path = os.path.join(save_dir, pdf_filename)

# 用户指定的固定URL前缀
fixed_url_prefix = "https://moor-smile.shec.edu.cn/rest/pdf/20250808"

# UUID组合 - 扩展更多可能性
uuid_combinations = [
    # 从成功下载的URL中提取的UUID
    "84519de1-8bb4-4bd1-b3fa-e610b20d4408",  
    
    # 之前使用过的UUID
    "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6",
    "f9e8d7c6-b5a4-3d2c-1b0a-fedcba987654",
    "7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d",
    "4d3c2b1a-5f6e-7d8c-9b0a-1f2e3d4c5b6a",
    "a1234567-89bc-def0-1234-56789abcdef0",
    "11112222-3333-4444-5555-666677778888",
    "abcdef12-3456-7890-abcd-ef1234567890",
    
    # 新增更多UUID组合，特别是那些可能与"人工智能"或"就业"相关的组合
    "aiem2025-0001-0001-0001-000000000001",  # AI Employment Market 2025
    "aieffect-2025-0000-0000-000000000001",  # AI Effect 2025
    "jobimpact-0000-2025-0000-000000000001",  # Job Impact 2025
    "20250808-0000-0000-0000-000000000001",  # 包含日期的UUID
    "2025-0808-0000-0000-000000000001",     # 包含日期的UUID变体
    "0000-2025-0808-0000-000000000001",     # 包含日期的UUID变体
    "08082025-0000-0000-0000-000000000001",  # 包含日期的UUID变体
    
    # 随机生成的UUID
    "e4b89a4e-b810-4360-ba3c-8a2e9d8f7c6b",
    "5f9e3b8d-1a7c-4d2b-9e6f-8c3a2d7f4b9a",
    "9a8b7c6d-5e4f-3a2b-1c0d-9e8f7a6b5c4d",
    "1234abcd-5678-90ef-ab12-34567890abcd",
    "abcd1234-ef56-ab78-cd90-ef1234567890",
    "00000000-0000-0000-0000-000000000001",
    "00000000-0000-0000-0000-000000000010",
    "00000000-0000-0000-0000-000000000100",
    "00000000-0000-0000-0000-000000001000",
    "00000000-0000-0000-0000-000000010000",
    "00000000-0000-0000-0000-000000100000",
    "00000000-0000-0000-0000-000001000000",
    "00000000-0000-0000-0000-000010000000",
    "00000000-0000-0000-0000-000100000000",
    "00000000-0000-0000-0000-001000000000",
    "00000000-0000-0000-0000-010000000000",
    "00000000-0000-0000-0000-100000000000",
    "00000000-0000-0000-0001-000000000000",
    "00000000-0000-0000-0010-000000000000",
    "00000000-0000-0000-0100-000000000000",
    "00000000-0000-0000-1000-000000000000",
    "00000000-0000-0001-0000-000000000000",
    "00000000-0000-0010-0000-000000000000",
    "00000000-0000-0100-0000-000000000000",
    "00000000-0000-1000-0000-000000000000",
    "00000000-0001-0000-0000-000000000000",
    "00000000-0010-0000-0000-000000000000",
    "00000000-0100-0000-0000-000000000000",
    "00000000-1000-0000-0000-000000000000",
    "00000001-0000-0000-0000-000000000000",
    "00000010-0000-0000-0000-000000000000",
    "00000100-0000-0000-0000-000000000000",
    "00001000-0000-0000-0000-000000000000",
    "00010000-0000-0000-0000-000000000000",
    "00100000-0000-0000-0000-000000000000",
    "01000000-0000-0000-0000-000000000000",
    "10000000-0000-0000-0000-000000000000"
]

# 不同的HTTP请求头 - 轮换使用以模拟不同的浏览器
user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"
]

def download_pdf(uuid):
    """使用指定的UUID尝试下载PDF文件"""
    try:
        # 构建完整URL路径
        url_path = f"{fixed_url_prefix}/{uuid}/{pdf_filename}"
        
        # 正确编码URL，只编码路径部分
        url_parts = list(urllib.parse.urlparse(url_path))
        url_parts[2] = urllib.parse.quote(url_parts[2])  # 编码path部分
        encoded_url = urllib.parse.urlunparse(url_parts)
        
        print(f"尝试UUID: {uuid}")
        print(f"编码后URL: {encoded_url}")
        
        # 随机选择用户代理
        headers = {'User-Agent': random.choice(user_agents)}
        
        # 创建请求对象
        req = urllib.request.Request(encoded_url, headers=headers)
        
        # 设置超时时间为15秒
        with urllib.request.urlopen(req, timeout=15) as response:
            # 检查响应状态码
            if response.status == 200:
                # 检查Content-Type是否为PDF
                content_type = response.getheader('Content-Type')
                if content_type and 'pdf' in content_type.lower():
                    # 读取并写入文件
                    data = response.read()
                    with open(pdf_save_path, 'wb') as out_file:
                        out_file.write(data)
                    
                    # 验证文件大小
                    if os.path.exists(pdf_save_path):
                        file_size = os.path.getsize(pdf_save_path)
                        if file_size > 100:  # 确保文件不为空
                            return True, file_size
                        else:
                            print(f"警告: 下载的文件可能是空的 (大小: {file_size} 字节)")
                            os.remove(pdf_save_path)
                            return False, 0
                else:
                    print(f"警告: 响应内容不是PDF文件 (Content-Type: {content_type})")
                    return False, 0
            else:
                print(f"HTTP错误: {response.status}")
                return False, 0
    except urllib.error.HTTPError as e:
        print(f"HTTP错误: {e.code}")
        return False, 0
    except urllib.error.URLError as e:
        print(f"URL错误: {str(e)}")
        return False, 0
    except Exception as e:
        print(f"请求错误: {str(e)}")
        return False, 0

def main():
    print(f"开始尝试下载'{pdf_filename}'")
    print(f"保存路径: {pdf_save_path}")
    print(f"固定URL前缀: {fixed_url_prefix}")
    print(f"尝试UUID数量: {len(uuid_combinations)}")
    
    start_time = time.time()
    total_attempts = 0
    success = False
    
    # 尝试所有UUID组合
    for uuid in uuid_combinations:
        if success:
            break
            
        total_attempts += 1
        success, file_size = download_pdf(uuid)
        
        # 如果成功，退出循环
        if success:
            print(f"\nPDF文件下载成功！")
            print(f"保存路径: {pdf_save_path}")
            print(f"文件大小: {file_size / 1024:.2f} KB")
            break
        
        # 随机延迟0.5-1.5秒，避免请求过于频繁
        time.sleep(random.uniform(0.5, 1.5))
    
    end_time = time.time()
    
    if not success:
        print(f"\n所有UUID尝试都失败了。")
        print(f"总共尝试了 {total_attempts} 个UUID组合")
        print(f"固定URL前缀: {fixed_url_prefix}")
        print(f"可能的原因:")
        print("1. 文件可能不存在或已被移动")
        print("2. 服务器可能限制了访问权限")
        print("3. 需要正确的UUID值")
        print("4. 文件名可能不同")
        print("\n建议获取包含此PDF链接的HTML文件，或者确认文件是否存在于服务器上。")
    
    print(f"总耗时: {end_time - start_time:.2f} 秒")

if __name__ == "__main__":
    main()